package com.yf.dxapp.module.app.service.appuser;

import cn.iocoder.yudao.framework.common.exception.ServiceException;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import com.yf.dxapp.module.app.component.app.DouxinGroupComponent;
import com.yf.dxapp.module.app.controller.admin.appuser.vo.AppUserPageReqVO;
import com.yf.dxapp.module.app.controller.admin.appuser.vo.AppUserSaveReqVO;
import com.yf.dxapp.module.app.dal.dataobject.appuser.AppUserDO;
import com.yf.dxapp.module.app.dal.mysql.appuser.AppUserMapper;
import com.yf.dxapp.module.app.enums.app.LevelEnum;
import com.yf.dxapp.module.app.enums.app.UserStatusEnum;
import com.yf.dxapp.module.app.util.StringUtil;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.core.parameters.P;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;
import java.util.Set;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static com.yf.dxapp.module.app.enums.ErrorCodeConstants.DATA_NOT_EXISTS;
import static com.yf.dxapp.module.app.enums.ErrorCodeConstants.USER_MOBILE_EXISTS;


/**
 * 用户 Service 实现类
 *
 * @author 芋道源码
 */
@Service
@Validated
@Slf4j
public class AppUserServiceImpl implements AppUserService {

    @Resource
    private AppUserMapper appUserMapper;

    @Resource
    private DouxinGroupComponent douxinGroupComponent;

    @Override
    public Long createAppUser(AppUserSaveReqVO createReqVO) {
        // 插入
        if (validateMobileExists(createReqVO.getMobile())) {
            throw exception(USER_MOBILE_EXISTS);
        }
        AppUserDO appUser = BeanUtils.toBean(createReqVO, AppUserDO.class);
        appUserMapper.insert(appUser);
        // 返回
        return appUser.getId();
    }

    @Override
    public void updateAppUser(AppUserSaveReqVO updateReqVO) {
        // 校验存在
        validateAppUserExists(updateReqVO.getId(), updateReqVO.getMobile());
        // 更新
        AppUserDO updateObj = BeanUtils.toBean(updateReqVO, AppUserDO.class);
        appUserMapper.updateById(updateObj);
    }

    @Override
    public void deleteAppUser(Long id) {
        // 校验存在
        validateAppUserExists(id, null);
        // 删除
        appUserMapper.deleteById(id);
    }

    private boolean validateMobileExists(String mobile) {
        List<AppUserDO> appUserDOS = appUserMapper.selectList(AppUserDO::getMobile, mobile);
        return !appUserDOS.isEmpty();
    }

    private void validateAppUserExists(Long id, String mobile) {
        if (appUserMapper.selectById(id) == null) {
            throw exception(DATA_NOT_EXISTS);
        }
        if (StringUtils.isNotBlank(mobile)) {
            List<AppUserDO> appUserDOS = appUserMapper.selectList(AppUserDO::getMobile, mobile);
            if (appUserDOS.stream().anyMatch(u -> !Objects.equals(u.getId(), id))) {
                throw exception(USER_MOBILE_EXISTS);
            }
        }
    }

    @Override
    public AppUserDO getAppUser(Long id) {
        return appUserMapper.selectById(id);
    }

    @Override
    public PageResult<AppUserDO> getAppUserPage(AppUserPageReqVO pageReqVO) {
        return appUserMapper.selectPage(pageReqVO);
    }

    @Override
    public AppUserDO phoneRegister(String topCode, String phone) {
        if (!StringUtil.isPhone(phone)) {
            throw new ServiceException(-1, "手机号有误!");
        }
        if (StringUtil.isBlank(topCode)) { //统一放到公司卷卷下
            topCode = "15675234523";
//            throw new RRException("推荐人不存在");
        }
        AppUserPageReqVO req = new AppUserPageReqVO();
        req.setMobile(topCode);
        PageResult<AppUserDO> result = appUserMapper.selectPage(req);
        List<AppUserDO> list = result.getList();
        if (list.isEmpty()) {
            throw new ServiceException(-1, "推荐人不存在");
        }
        AppUserDO user = new AppUserDO();
        user.setPid(list.get(0).getId());
        user.setMobile(phone);
        user.setCode(phone);
        //游客
        Long levelByMobile = douxinGroupComponent.getLevelByMobile(phone);
        if(levelByMobile<5){ //级别ID小于五的就是基础
            user.setLevelId(LevelEnum.DZ.levelId);
        }else {
            user.setLevelId(LevelEnum.YK.levelId);
        }
//        user.setLevelId(levelByMobile);
        user.setStatus(UserStatusEnum.ACTIVE.getIndex());
        user.setTime(LocalDateTime.now());
        user.setPassword("888888");
        user.setRemark("APP小程序手机号注册");
        appUserMapper.insert(user);
        return user;
    }

    @Override
    public boolean signOff(Long userId, String reason) {
        if (userId == null) {
            return false;
        }
        log.info("用户{}操作注销账户，注销原因：{}", userId, reason);
        // 校验存在
        validateAppUserExists(userId, null);
        // 删除
        return appUserMapper.deleteById(userId) > 0;
    }

    @Override
    public List<AppUserDO> finByUserIds(Set<Long> publisherIds) {
        return appUserMapper.selectList(AppUserDO::getId, publisherIds);
    }

}